package ee.nutilovi.praktikaportaal.company;

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.http.*;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.gson.Gson;

@SuppressWarnings("serial")
public class RatingServlet extends HttpServlet {
			
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		long id = Long.parseLong(req.getParameter("companyId"));
		int vote = Integer.parseInt(req.getParameter("vote").substring(req.getParameter("vote").length() - 1));
		Entity company = getCompany(id);
		long votes = (long) company.getProperty("votes");
		long score = (long) company.getProperty("score");
		votes++;
		score = score + vote;
		company.setProperty("votes", votes);
		company.setProperty("score", score);
		saveCompany(company);
		
		String votesString = ((Long) votes).toString();
		String scoreString = ((Long) score).toString();
		
		Map<String, String> data = new LinkedHashMap<String, String>();
		data.put("votes", votesString);
		data.put("score", scoreString);
		
		String json = new Gson().toJson(data);
		
		resp.setContentType("application/json");
	    resp.setCharacterEncoding("UTF-8");
	    resp.getWriter().write(json);
	}
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		long id = Long.parseLong(req.getParameter("companyId"));
		Entity company = getCompany(id);
		String votes = company.getProperty("votes").toString();
		String score = company.getProperty("score").toString();
		
		Map<String, String> data = new LinkedHashMap<String, String>();
		data.put("votes", votes);
		data.put("score", score);
		
		String json = new Gson().toJson(data);
		
		resp.setContentType("application/json");
	    resp.setCharacterEncoding("UTF-8");
	    resp.getWriter().write(json);
	}
	
	private Entity getCompany(long id) {
		DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
		Key companyKey = KeyFactory.createKey("Company", id);
		Entity company = null;
		try {
			company = ds.get(companyKey);
		} catch (EntityNotFoundException e) {
			return company;
		}
		return company;
	}
	
	private void saveCompany(Entity company) {
		DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
		ds.put(company);
	}
}
